<template>
  <div class="shipping-management">
    <div class="page-header">
      <h2>包邮管理</h2>
    </div>

    <!-- 搜索区域 -->
    <div class="search-area">
      <el-form :model="searchForm" inline>
        <el-form-item label="包邮名称">
          <el-input v-model="searchForm.shippingName" placeholder="请输入包邮名称" clearable />
        </el-form-item>
        <el-form-item label="包邮类型">
          <el-select v-model="searchForm.shippingType" placeholder="请选择包邮类型" clearable>
            <el-option label="满x元包邮" :value="1" />
          </el-select>
        </el-form-item>
        <el-form-item label="适用范围">
          <el-select v-model="searchForm.shippingScope" placeholder="请选择适用范围" clearable>
            <el-option label="实物类" :value="1" />
            <el-option label="虚拟货物" :value="2" />
          </el-select>
        </el-form-item>
        <el-form-item label="包邮状态">
          <el-select v-model="searchForm.shippingState" placeholder="请选择状态" clearable>
            <el-option label="进行中" :value="1" />
            <el-option label="已终止" :value="2" />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="searchShippings">
            <el-icon><Search /></el-icon>
            搜索
          </el-button>
          <el-button @click="resetSearch">
            <el-icon><Refresh /></el-icon>
            重置
          </el-button>
          <el-button type="primary" @click="showAddDialog = true">
            <el-icon><Plus /></el-icon>
            新增包邮
          </el-button>
        </el-form-item>
      </el-form>
    </div>

    <!-- 表格区域 -->
    <div class="table-area">
      <el-table :data="shippingList" v-loading="loading" stripe>
        <el-table-column prop="shippingId" label="包邮ID" width="80" />
        <el-table-column prop="shippingName" label="包邮名称" width="200" />
        <el-table-column prop="shippingType" label="包邮类型" width="120">
          <template #default="{ row }">
            <el-tag type="primary">
              {{ getShippingTypeText(row.shippingType) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="shippingCon" label="包邮内容" width="200" />
        <el-table-column prop="shippingScope" label="适用范围" width="120">
          <template #default="{ row }">
            <el-tag :type="row.shippingScope === 1 ? 'success' : 'info'">
              {{ getShippingScopeText(row.shippingScope) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="shippingState" label="包邮状态" width="120">
          <template #default="{ row }">
            <el-tag :type="getShippingStateType(row.shippingState)">
              {{ getShippingStateText(row.shippingState) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="startTime" label="开始时间" width="180" />
        <el-table-column prop="endTime" label="结束时间" width="180" />
        <el-table-column label="操作" width="200" fixed="right">
          <template #default="{ row }">
            <el-button size="small" @click="editShipping(row)">
              <el-icon><Edit /></el-icon>
              编辑
            </el-button>
            <el-button size="small" type="danger" @click="deleteShipping(row.shippingId)">
              <el-icon><Delete /></el-icon>
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div class="pagination">
        <el-pagination
          v-model:current-page="pagination.currentPage"
          v-model:page-size="pagination.pageSize"
          :page-sizes="[10, 20, 50, 100]"
          :total="pagination.total"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </div>

    <!-- 新增/编辑对话框 -->
    <el-dialog
      :title="isEdit ? '编辑包邮' : '新增包邮'"
      v-model="showAddDialog"
      width="600px"
      @close="resetForm"
    >
      <el-form :model="shippingForm" :rules="shippingRules" ref="shippingFormRef" label-width="120px">
        <el-form-item label="包邮名称" prop="shippingName">
          <el-input v-model="shippingForm.shippingName" placeholder="请输入包邮名称" />
        </el-form-item>
        <el-form-item label="包邮类型" prop="shippingType">
          <el-select v-model="shippingForm.shippingType" placeholder="请选择包邮类型">
            <el-option label="满x元包邮" :value="1" />
          </el-select>
        </el-form-item>
        <el-form-item label="包邮内容" prop="shippingCon">
          <el-input v-model="shippingForm.shippingCon" type="textarea" placeholder="请输入包邮内容" />
        </el-form-item>
        <el-form-item label="适用范围" prop="shippingScope">
          <el-select v-model="shippingForm.shippingScope" placeholder="请选择适用范围">
            <el-option label="实物类" :value="1" />
            <el-option label="虚拟货物" :value="2" />
          </el-select>
        </el-form-item>
        <el-form-item label="包邮状态" prop="shippingState">
          <el-select v-model="shippingForm.shippingState" placeholder="请选择状态">
            <el-option label="进行中" :value="1" />
            <el-option label="已终止" :value="2" />
          </el-select>
        </el-form-item>
        <el-form-item label="开始时间" prop="startTime">
          <el-date-picker
            v-model="shippingForm.startTime"
            type="datetime"
            placeholder="请选择开始时间"
            format="YYYY-MM-DD HH:mm:ss"
            value-format="YYYY-MM-DD HH:mm:ss"
          />
        </el-form-item>
        <el-form-item label="结束时间" prop="endTime">
          <el-date-picker
            v-model="shippingForm.endTime"
            type="datetime"
            placeholder="请选择结束时间"
            format="YYYY-MM-DD HH:mm:ss"
            value-format="YYYY-MM-DD HH:mm:ss"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="showAddDialog = false">取消</el-button>
        <el-button type="primary" @click="submitForm">确定</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Plus, Search, Refresh, Edit, Delete } from '@element-plus/icons-vue'
import { shippingApi } from '@/api/shipping'

// 响应式数据
const loading = ref(false)
const shippingList = ref([])
const showAddDialog = ref(false)
const isEdit = ref(false)
const shippingFormRef = ref()

// 搜索表单
const searchForm = reactive({
  shippingName: '',
  shippingType: null,
  shippingScope: null,
  shippingState: null
})

// 分页数据
const pagination = reactive({
  currentPage: 1,
  pageSize: 10,
  total: 0
})

// 包邮表单
const shippingForm = reactive({
  shippingId: null,
  shippingName: '',
  shippingType: 1,
  shippingCon: '',
  shippingScope: null,
  shippingState: 1,
  startTime: '',
  endTime: ''
})

// 表单验证规则
const shippingRules = {
  shippingName: [
    { required: true, message: '请输入包邮名称', trigger: 'blur' }
  ],
  shippingType: [
    { required: true, message: '请选择包邮类型', trigger: 'change' }
  ],
  shippingCon: [
    { required: true, message: '请输入包邮内容', trigger: 'blur' }
  ],
  shippingScope: [
    { required: true, message: '请选择适用范围', trigger: 'change' }
  ],
  shippingState: [
    { required: true, message: '请选择包邮状态', trigger: 'change' }
  ],
  startTime: [
    { required: true, message: '请选择开始时间', trigger: 'change' }
  ],
  endTime: [
    { required: true, message: '请选择结束时间', trigger: 'change' }
  ]
}

// 获取包邮类型文本
const getShippingTypeText = (type) => {
  const typeMap = {
    1: '满x元包邮'
  }
  return typeMap[type] || '未知'
}

// 获取适用范围文本
const getShippingScopeText = (scope) => {
  const scopeMap = {
    1: '实物类',
    2: '虚拟货物'
  }
  return scopeMap[scope] || '未知'
}

// 获取包邮状态文本
const getShippingStateText = (state) => {
  const stateMap = {
    1: '进行中',
    2: '已终止'
  }
  return stateMap[state] || '未知'
}

// 获取包邮状态标签类型
const getShippingStateType = (state) => {
  const stateMap = {
    1: 'success',
    2: 'danger'
  }
  return stateMap[state] || 'info'
}

// 搜索包邮
const searchShippings = async () => {
  loading.value = true
  try {
    const response = await shippingApi.getShippings(searchForm)
    if (response.code === 200) {
      shippingList.value = response.data || []
      pagination.total = shippingList.value.length
    }
  } catch (error) {
    console.error('搜索包邮失败:', error)
  } finally {
    loading.value = false
  }
}

// 重置搜索
const resetSearch = () => {
  Object.assign(searchForm, {
    shippingName: '',
    shippingType: null,
    shippingScope: null,
    shippingState: null
  })
  searchShippings()
}

// 编辑包邮
const editShipping = (row) => {
  isEdit.value = true
  Object.assign(shippingForm, row)
  showAddDialog.value = true
}

// 删除包邮
const deleteShipping = async (id) => {
  try {
    await ElMessageBox.confirm('确定要删除这个包邮活动吗？', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })

    const response = await shippingApi.deleteShipping(id)
    if (response.code === 200) {
      ElMessage.success('删除成功')
      searchShippings()
    }
  } catch (error) {
    if (error !== 'cancel') {
      console.error('删除包邮失败:', error)
    }
  }
}

// 提交表单
const submitForm = async () => {
  try {
    await shippingFormRef.value.validate()

    const response = isEdit.value
      ? await shippingApi.updateShipping(shippingForm)
      : await shippingApi.addShipping(shippingForm)

    if (response.code === 200) {
      ElMessage.success(isEdit.value ? '修改成功' : '新增成功')
      showAddDialog.value = false
      searchShippings()
    }
  } catch (error) {
    console.error('提交失败:', error)
  }
}

// 重置表单
const resetForm = () => {
  Object.assign(shippingForm, {
    shippingId: null,
    shippingName: '',
    shippingType: 1,
    shippingCon: '',
    shippingScope: null,
    shippingState: 1,
    startTime: '',
    endTime: ''
  })
  isEdit.value = false
  shippingFormRef.value?.resetFields()
}

// 分页处理
const handleSizeChange = (val) => {
  pagination.pageSize = val
  searchShippings()
}

const handleCurrentChange = (val) => {
  pagination.currentPage = val
  searchShippings()
}

// 初始化
onMounted(() => {
  searchShippings()
})
</script>

<style scoped>
.shipping-management {
  padding: 20px;
}

.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.search-area {
  background: white;
  padding: 20px;
  border-radius: 8px;
  margin-bottom: 20px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
}

.table-area {
  background: white;
  padding: 20px;
  border-radius: 8px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
}

.pagination {
  margin-top: 20px;
  display: flex;
  justify-content: center;
}
</style>
